using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ProjectEuler.Core.Helpers;

namespace ProjectEuler.Core
{
    public class Problem38 : IProjectEulerProblem
    {
        protected IEnumerable<long> PandigitalProducts()
        {
            for (int i = 2; i <= 10; i++)
            {
                var set = Enumerable.Range(1, i).ToList();
                for (int j = 1; j <= 10000; j++)
                {
                    var ias = new SingleNumberAndSet(j, set);
                    var product = ias.ConcatenateProduct;
                    if (MathHelper.IsPandigital(product))
                    {
                        yield return product;
                    }
                }
            }
        }

        public int Number
        {
            get { return 38; }
        }

        public string Description
        {
            get { return "What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n  1?"; }
        }

        public string Answer
        {
            get
            {
                return PandigitalProducts().Max().ToString();
            }
        }

        public class SingleNumberAndSet
        {
            public SingleNumberAndSet(int integer, IEnumerable<int> set)
            {
                SingleNumber = integer;
                Set = set;
            }
            public long SingleNumber { get; private set; }
            public IEnumerable<int> Set { get; private set; }

            public long ConcatenateProduct
            {
                get
                {
                    var concat = new StringBuilder();
                    foreach (var i in Set)
                    {
                        concat.Append(i*SingleNumber);
                    }
                    if(concat.Length > 9)
                    {
                        return 0;               // numbers with length > 9 are irrelevant
                    }
                    return long.Parse(concat.ToString());
                }
            }
        }
    }

    [TestFixture]
    public class Problem38Tests : Problem38
    {
        [Test]
        public void Then_192384576_should_be_in_the_pandigital_numbers()
        {
            var products = PandigitalProducts();
            Assert.IsTrue(products.Contains(192384576));
        }

    }
}